package com.spzx.cloud.gateway.filter;

import io.micrometer.common.util.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        // 获取用户 username 参数
        String username = request.getQueryParams().getFirst("username");
        // 判断
        if (StringUtils.isBlank(username)) {
            // 响应页面结果
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 对页面作出响应
            return exchange.getResponse().setComplete();
        }

        // 放行
        return chain.filter(exchange);
    }

    // 设置过滤器的优先级
    @Override
    public int getOrder() {
        return 0;
    }

}
